import os
import sys
import log
from urllib import quote_plus, unquote_plus


EQL_S  = '='
SEP_S  = '&'

class PluginKeyError( Exception ):
    pass
    
    
        
class Key:

    _prefix  = '__key__'
    
    
    @staticmethod
    def build_url(prefix, path=None, words=None, **kwargs):
    
        if not path: 
            path = os.getcwd()
        if words: 
            for kw in kwargs:
                words[kw] = kwargs[kw]
            kwargs = words
            
        key = Key.build_key(prefix, kwargs)
        url = '%s?%s' % (path, key)
        
        return url
    # - EOM -
    
    
    @staticmethod
    def build_key(prefix, words=None, **kwargs):

        if words: kwargs = words
        key = '%s%s' % (prefix, (SEP_S*2))
        
        for kw in kwargs:
            val = quote_plus(repr(kwargs[kw]))
            key = '%s%s%s%s%s' % (key, kw, EQL_S, val, SEP_S)
            
        return key
    # - EOM -   

    
    def __init__(self, key=None, **kwargs):
    
        if key and key != 'new':
            self.open(key)
            
        for kw in kwargs:
            if kwargs[kw] is '': kwargs[kw] = None
            
        self.__dict__.update(kwargs)
    # - EOM -

    
    def __getattr__(self, name):
        return None
    # - EOM -
   
    
    def __setattr__(self, name, value):
        if name.startswith('_'):
            self.__dict__[name] = value
            return
        if value == None: 
            return
        else: self.__dict__[name] = value
    # - EOM -
    
    
    def __repr__(self):
        return self.build_url(self._prefix, words=self.__dict__)
    # - EOM -
        
        
    def __str__(self):
        val = []
        for var in self.__dict__:
            if var.startswith('_') or self.__dict__[var] == None: 
                continue
            else:   
                val.append( '%s[%s]' % ( var, repr(self.__dict__[var]) ) )
        return ', '.join(val)
    # - EOM -  
      
    
    def __hash__(self):
        return hash( repr( self ) )
    # - EOM -
    
    
    def open(self, key):
            
        key = unquote_plus(key)
        if key.startswith('?'): key = key[1:]
        
        try:
            prefix, key = key.split(SEP_S * 2)
            key = key.replace(SEP_S, ', ')
            
        except: raise PluginKeyError( 'Could not generate plugin key' )
            
        else:
            try:    exec 'key = Key(%s)' % (key)
            except: raise PluginKeyError( 'Could not create key object' )              
            else:
                self.__dict__.update(key.__dict__)
                self._prefix = prefix
                if self._verbose: 
                    log.debug( 'addon.NRK.key %s' % str( self ) )
                return True
    # - EOM -

    
    def getkey(self, prefix='__key__'):
        return self.build_key(prefix, words=self.__dict__)
    # - EOM -


    def geturl(self, prefix='__key__', path=None):
        return self.build_url(prefix, words=self.__dict__)
    # - EOM
    

class State:
    
    class __impl(Key):
        pass

    __inst = None

    
    def __init__(self, key=None):
        if State.__inst is None:
            if not key: 
                key = ""
            State.__inst = State.__impl(key)
        self.__dict__['_State__inst'] = State.__inst

        
    def __getattr__(self, attr):
        return getattr(self.__inst, attr)

        
    def __setattr__(self, attr, value):
        return setattr(self.__inst, attr, value)




if len(sys.argv) >= 2: arg = sys.argv[2]
else: arg = ''

State( arg )


if __name__ == '__main__':
    key = Key( age=12 )
    key.name = 'my_name'
    print repr( key )